# -*- coding: utf-8 -*-
"""
@Time ： 2025/7/27 11:31
@Auth ： 韩明航
"""
import csv

# 定义输入文件路径和输出文件路径
input_file_path = '成都.csv'
output_file_path = '成都_选定列表.csv'

# 定义需要提取的列名
columns_to_extract = ['景区名称', '区域名称', '景区地址', '星级', '景区标签列表', '景区特点描述']

# 读取CSV文件并提取特定列
def extract_columns(input_path, output_path, columns):
    with open(input_path, mode='r', encoding='utf-8') as infile, \
         open(output_path, mode='w', encoding='utf-8', newline='') as outfile:
        reader = csv.DictReader(infile)
        writer = csv.DictWriter(outfile, fieldnames=columns)
        writer.writeheader()
        for row in reader:
            extracted_row = {col: row[col] for col in columns if col in row}
            writer.writerow(extracted_row)

# 调用函数提取特定列
extract_columns(input_file_path, output_file_path, columns_to_extract)

# 读取提取后的文件并生成三元组
def generate_triples(input_path):
    triples = []
    with open(input_path, mode='r', encoding='utf-8') as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            name = row['景区名称']
            location = row['景区地址']
            level = row['星级']
            features = row['景区特点描述']
            tags = row['景区标签列表']

            # 构建三元组
            if location:
                triples.append((name, '位于', location))
            if level:
                triples.append((name, '属于', f"{level} 级景区"))
            if features:
                features_list = features.split('，')  # 使用中文逗号分隔
                for feature in features_list:
                    triples.append((name, '特点是', feature.strip()))
            if tags:
                tags_list = eval(tags)  # 将字符串转换为列表
                for tag in tags_list:
                    triples.append((name, '标签', tag.strip()))

    return triples

# 生成三元组
triples = generate_triples(output_file_path)

# 打印三元组
for triple in triples:
    print(triple)

#保存三元组
def save_triples_to_csv(triples, output_path):
    with open(output_path, mode='w', encoding='utf-8', newline='') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(['主体', '关系', '宾语'])  # 写入表头
        for triple in triples:
            writer.writerow(triple)

save_triples_to_csv(triples, "成都_三元组.csv")